package cn.school.controller;


import cn.school.config.MinioConfig;
import cn.school.vo.OcrVo;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.GeneralBasicOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.GeneralBasicOCRResponse;
import com.tencentcloudapi.ocr.v20181119.models.TextDetection;
import io.minio.MinioClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Base64;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {
    @Resource
    private MinioClient minioClient;

    @Resource
    private MinioConfig minioConfig;
    @Value("${tencentcloud.secretId}")
    private String secretId;

    @Value("${tencentcloud.secretKey}")
    private String secretKey;

    @Value("${tencentcloud.region}")
    private String region;
    private static final Logger log = LoggerFactory.getLogger(FileController.class);
    @RequestMapping("/upload")
    public String upload(MultipartFile file) throws Exception{
        try
        {
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") +
                    getFileExtension(originalFilename);

            log.info("准备上传文件，大小: {}字节, 名称: {}, 内容类型: {}",
                    file.getSize(), fileName, file.getContentType());

            // 首先将MultipartFile转成临时文件，然后使用putObject上传临时文件
            java.nio.file.Path tempFile = java.nio.file.Files.createTempFile("upload_", getFileExtension(originalFilename));
            file.transferTo(tempFile.toFile());

            log.info("已创建临时文件: {}", tempFile);

            // 使用文件上传而不是流，避免分片问题
            minioClient.putObject(
                    minioConfig.getBucketName(),
                    fileName,
                    tempFile.toString(),
                    null
            );

            // 删除临时文件
            java.nio.file.Files.deleteIfExists(tempFile);

            //http://121.43.130.89:9000/zys/filename
            String fileUrl = minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + fileName;

            log.info("文件上传成功，URL: {}", fileUrl);
            return fileUrl;
        }
        catch (Exception e)
        {
            return "上传失败";
        }
    }
    private String getFileExtension(String filename) {
        if (filename == null) {
            return "";
        }
        int lastDotIndex = filename.lastIndexOf('.');
        return lastDotIndex == -1 ? "" : filename.substring(lastDotIndex);
    }
    @RequestMapping("/uploadOcr")
    public OcrVo uploadOcr(MultipartFile file){
        try
        {
            OcrVo ocrVo = new OcrVo();
            // 1. 转换文件为Base64
            byte[] fileBytes = file.getBytes();
            String imageBase64 = Base64.getEncoder().encodeToString(fileBytes);

            // 2. 调用腾讯云OCR服务
            String resultText = callTencentOcrService(imageBase64);

            // 3. 创建OCR结果对象
            ocrVo.setQuestionDetail(resultText);

            String originalFilename = file.getOriginalFilename();
            // 生成唯一文件名
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") +
                    getFileExtension(originalFilename);
            log.info("准备上传文件，大小: {}字节, 名称: {}, 内容类型: {}",
                    file.getSize(), fileName, file.getContentType());
            // 首先将MultipartFile转成临时文件，然后使用putObject上传临时文件
            java.nio.file.Path tempFile = java.nio.file.Files.createTempFile("upload_", getFileExtension(originalFilename));
            file.transferTo(tempFile.toFile());
            log.info("已创建临时文件: {}", tempFile);
            // 使用文件上传而不是流，避免分片问题
            minioClient.putObject(
                    minioConfig.getBucketName(),
                    fileName,
                    tempFile.toString(),
                    null
            );
            // 删除临时文件
            java.nio.file.Files.deleteIfExists(tempFile);
            // 按照要求构造文件访问路径: http://121.43.130.89:9000/zys/filename
            String fileUrl = minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + fileName;
            log.info("文件上传成功，URL: {}", fileUrl);
            ocrVo.setImgUrl(fileUrl);
            return ocrVo;
        }
        catch (Exception e)
        {
            OcrVo ocrVo = new OcrVo();
            ocrVo.setImgUrl("图片上传失败");
            ocrVo.setQuestionDetail("图片识别失败");
            return ocrVo;
        }
    }
    private String callTencentOcrService(String imageBase64) throws TencentCloudSDKException {
        Credential cred = new Credential(secretId, secretKey);
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("ocr.tencentcloudapi.com");
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        OcrClient client = new OcrClient(cred, region, clientProfile);

        GeneralBasicOCRRequest req = new GeneralBasicOCRRequest();
        req.setImageBase64(imageBase64);
        GeneralBasicOCRResponse resp = client.GeneralBasicOCR(req);

        StringBuilder result = new StringBuilder();
        for (TextDetection text : resp.getTextDetections()) {
            result.append(text.getDetectedText()).append("\n");
        }
        return result.toString();
    }
}
